<!-- 轮播图/视频 -->
<template>
  <div>
    <el-upload
      ref="upload"
      :class="{showUpLoad: disabled ||fileList.length==limit }"
      action="#"
      :limit="limit"
      list-type="picture-card"
      :file-list="fileList"
      :on-change="onChange"
      :on-success="onSuccess"
      :on-remove="onRemove"
      :on-preview="handlePictureCardPreview"
      :accept="accept"
      :on-exceed="onExceed"
      :auto-upload="false"
      :disabled="disabled"
    >
      <template v-if="!disabled">
        <i class="el-icon-plus"></i>
      </template>
      <div
        v-if="accept === '.doc, .docx, .pdf, .xls, .xlsx, .txt'&&!disabled"
        slot="tip"
        class="el-upload__tip"
      >可上传多种pdf,xls,doc文件</div>

      <template slot="file" slot-scope="{ file }">
        <div v-loading="loading" class="mask">
          <!-- 遮罩层 -->
          <div class="above">
            <div class="view el-icon-zoom-in" @click="view(file)"></div>
            <i
              v-if="!disabled"
              class="delete el-icon-delete"
              @click="onRemove(file)"
            ></i>
          </div>
          <div
            style="height: 100%;     display: flex;
          align-items: center;
          justify-content: center;"
          >{{ file.fileName }}</div>
          <!-- <iframe :src="'https://view.officeapps.live.com/op/view.aspx?src=' + file.url" controls muted width="100%" height="100%" /> -->
        </div>
      </template>
    </el-upload>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="dialogVisible" append-to-body top="0">
      <iframe
        v-if="dialogImageUrlName.includes('.pdf') || dialogImageUrlName.includes('.txt')"
        id="iframe"
        class="iframe"
        :src="page_url"
        frameborder="0"
        width="100%"
      ></iframe>
      <iframe
        v-else
        id="iframe"
        class="iframe"
        :src="'https://view.officeapps.live.com/op/view.aspx?src=' + dialogImageUrl"
        controls
        muted
        width="100%"
      ></iframe>
    </el-dialog>
    <!-- 预览视频 -->
    <el-dialog :visible.sync="dialogViewVideo" append-to-body top="0">
      <video :src="dialogVideo" controls width="100%"></video>
    </el-dialog>
  </div>
</template>

<script>
import DocumentApi from "@/api/document"; // 文件上传/下载
import axios from "axios";
// import Api from '@/utils/tool/api' // 文件相关
export default {
  name: "UploadImg",
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: Array,
      default: () => [],
    },
    accept: {
      type: String,
      default: "jpg/mp4",
    },
    limit: {
      type: Number,
      default: 9,
    },
  },
  data() {
    return {
      dialogVisible: false, // 图片弹窗
      dialogImageUrl: "", // 预览图片
      dialogImageUrlName: "", // 预览图片
      page_url: "",
      dialogViewVideo: false, // 视频弹窗
      dialogVideo: "", // 预览视频
      loading: true, // 加载效果
      // fileList: []
    };
  },
  computed: {
    // // 负责回显的数组
    fileList: {
      get() {
        return this.value;
      },
      set(val) {
        return val;
        // this.$emit('input', val)
      },
    },
  },
  methods: {
    onChange(file, fileList) {
      const a = [];
      fileList.forEach((res) => {
        if (res.fileType) {
          a.push(res); // 获取带有res.fileType的结构（和fileList相比少了最后一个添加的数据），表示新加之前的数据；
        }
      });
      const index = a.findIndex((v) => {
        return v.fileType == "video/mp4";
      });
      //
      this.loading = true;
      const dataForm = new FormData();
      dataForm.append("file", file.raw);
      dataForm.append("moduleType", "PLATFORMDEVICE");
      dataForm.append("upDownType", "FTP");
      // console.log('file.raw.type',file.raw.type);
      // return
      if (
        file.raw.type == "application/pdf" ||
        file.raw.type == "application/msword" ||
        file.raw.type == "application/vnd.ms-excel" ||
        file.raw.type ==
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
        file.raw.type ==
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        // file.raw.type == "text/plain"
      ) {
        DocumentApi.upload(dataForm)
          .then((res) => {
            // console.log("**********", res);
            let url = "";
            url = `${
              this.$webServiceUrl + "common/file/upDown/download"
            }?fileId=${
              res.data.fileId
            }%26upDownType=FTP%26moduleType=PLATFORMDEVICE`;
            this.fileList.push({
              url: url,
              fileType: file.raw.type,
              fileName: res.fileName,
            });
            // console.log(this.fileList)
            this.$emit("input", {
              list: this.fileList,
              obj: {
                url: url,
                fileType: file.raw.type,
                fileName: res.data.fileName,
              },
            }); // 传递给父组件 fileIdList 图片回显
            // this.$emit('addFileId', res.data) // 传递给父组件  图片数据
            this.$message.success("上传成功！");
            this.$emit("resetImg");
            this.loading = false;
          })
          .catch(() => {
            fileList.splice(-1, 1);
            this.$message.error("上传失败！");
          });
      } else {
        this.$message.error("pdf,doc,xls,txt类型的文件");
        fileList.splice(-1, 1);
        return;
      }
    },
    onRemove(file) {
      // this.fileList.splice(
      //   this.fileList.findIndex(i => i.url === file.url),
      //   1
      // );
      // console.log("this.fileList", this.fileList);
      // this.$emit("input", this.fileList);
      this.$emit("delectFileId", file);
    },
    // 文件超出个数限制时
    onExceed(file) {
      this.$message.info(`最多上传${this.limit}张`);
    },
    // loading设置
    onSuccess(response, file, fileList) {},
    // 预览
    view(file) {
      console.log(file);
      this.dialogVisible = true; // 图片弹窗
      this.dialogImageUrl = file.url; // 预览图片
      this.dialogImageUrlName = file.fileName; //
      this.makePdf(file.url);
      // console.log('预览',file);
    },
    makePdf(url) {
      // 把孙悟空替换为了猪八戒
      var newstr = url.replace(/%26/g, "&");
      //  console.log(newstr);
      axios.get(newstr, { responseType: "blob" }).then((res) => {
        const { data, status } = res;
        let binaryData = [];
        binaryData.push(data); // res 后台返回的流数据
        let pdfUrl = "";
        pdfUrl = window.URL.createObjectURL(
          new Blob(binaryData, { type: "application/pdf" })
        );
        this.page_url = pdfUrl;
      });
    },
    handlePictureCardPreview(file) {},
    // 清空
    clearFiles() {
      this.$refs.upload.clearFiles();
    },
  },
};
</script>

<style scoped lang="scss">
/* 隐藏el-upload */
.showUpLoad {
  ::v-deep .el-upload {
    display: none;
  }
}
/* loading */
::v-deep .el-loading-mask {
  width: 100%;
}
/*  */
.mask {
  background: #fff;
  width: 100%;
  height: 100%;
  position: relative;
  /*  */
  &:hover .above {
    background: rgba(0, 0, 0, 0.5);
  }
  .above {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 100;
    .view {
      display: none;
    }
    display: flex;
    justify-content: center;
    align-items: center;
    &:hover .view {
      display: inline;
      color: #fff;
      font-size: 20px;
      text-align: center;
      cursor: pointer;

      // position: absolute;
      // left: 20%;
      // bottom: 42%;
    }
    .delete {
      display: none;
    }
    &:hover .delete {
      display: inline;
      color: #fff;
      font-size: 20px;
      text-align: center;
      cursor: pointer;
      margin-left: 10px;
      // position: absolute;
      // right: 20%;
      // bottom: 42%;
    }
  }

  video {
    width: 300px;
    height: 180px;
    position: absolute;
    top: -30px;
    z-index: 2;
  }
}
::v-deep {
  .el-upload-list__item {
    width: 90px;
    height: 90px;
  }
  .el-upload--picture-card {
    width: 90px;
    height: 90px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
  }
}
.iframe {
  height: 80vh;
}
</style>
